package com.adou.d10.reflect;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class TestConstructor {

    @Test
    public void testAllConstructors(){
        // 1
        Class c = Cat.class;

        // 2 获取类全部构造器 只能查public
//        Constructor[] constructors = c.getConstructors();
        Constructor[] constructors = c.getDeclaredConstructors();

        // 打印构造器
        for (Constructor constructor : constructors) {
            System.out.println(constructor.getName() + " - " + constructor.getParameterCount());
        }


    }

    @Test
    public void getConstructors() throws Exception {
        // 1
        Class c = Cat.class;

        // 2获取无参数构造器（只能是public）
//        Constructor cConstructor = c.getConstructor();
        Constructor constructor = c.getDeclaredConstructor();
        System.out.println(constructor.getName() + " - " + constructor.getParameterCount());

        constructor.setAccessible(true);
        Cat cat = (Cat)constructor.newInstance();// IllegalAccessException:
        System.out.println(cat);



        // 3.获取参数构造器
        Constructor constructor2 = c.getDeclaredConstructor(String.class, int.class);
        System.out.println(constructor2.getName() + " - " + constructor2.getParameterCount());

        // 4.获取有参构造器
        Cat cat2 = (Cat)constructor2.newInstance("叮当猫", 2);// IllegalArgumentException:
        System.out.println(cat2);
    }




}
